import cv2
import os
import sys
import numpy as np

def detect():
    face_casade = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml')
    eye_cascade = cv2.CascadeClassifier('./haarcascades/haarcascade_eye.xml')
    camera = cv2.VideoCapture(0)

    cv2.namedWindow('camera')

    ret, frame = camera.read()

    while ret:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_casade.detectMultiScale(gray, 1.3, 5)

        for (x, y, w, h) in faces:
            img = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1)

            roi_gray = gray[y: y + h, x:x+w]
            eyes = eye_cascade.detectMultiScale(roi_gray, 1.03, 5, 0, (5, 5))
            for(ex, ey, ew, eh) in eyes:
                cv2.rectangle(img, (ex + x, ey + y), (ex + ew + x, ey + eh + y), (255, 0, 0), 1)
            
        cv2.imshow('camera', frame)
        if cv2.waitKey(1) != -1:
            break

        ret, frame = camera.read()
    
    cv2.destroyAllWindows()
    camera.release()

def generate():
    face_cascade = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml')
    eye_cascade = cv2.CascadeClassifier('./haarcascades/haarcascade_eye.xml')
    camera = cv2.VideoCapture(0)

    cv2.namedWindow('camera')

    ret, frame = camera.read()
    count = 0
    while ret:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)

        for (x, y, w, h) in faces:
            img = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1)
            f = cv2.resize(gray[y:y+h, x:x+w], (200, 200))
            cv2.imwrite('byons/%s.pgm' % str(count), f)
            count += 1
            
        cv2.imshow('camera', frame)
        if cv2.waitKey(1) != -1:
            break
        ret, frame = camera.read()
    
    cv2.destroyAllWindows()
    camera.release()

def read_images(path, sz=None):
    images, IDs = [], []
    
    csvFile = open(path)
    maplist = csvFile.readlines()
    csvFile.close()

    for line in maplist:
        [image, id] = line.split(";")
        images.append(cv2.imread(image, cv2.IMREAD_GRAYSCALE))
        IDs.append(int(id))

    return [images, IDs]

def face_rec():
    [X, y] = read_images('./samples')

if __name__ == '__main__':
    generate()